package com.shwread.android.ui.customview;

import android.app.Activity;
import android.support.v4.view.PagerAdapter;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;

import com.GlideUtil;
import com.shwread.android.qysw10000213.R;

import java.util.HashMap;
import java.util.List;

import logic.bean.BannerInfo;
import logic.constants.DefaultConsts;

public class ViewPagerAdapter extends PagerAdapter {

	private Activity activity;
	private List<BannerInfo> bannerList;
	private HashMap<Integer, View> views;
	private BannerOnClickListener listener;
	private int size ;

	public ViewPagerAdapter(Activity activity, /*List<BannerInfo> bannerList,*/ HashMap<Integer, View> views, BannerOnClickListener bannerOnClickListener) {
		this.activity = activity;
//		this.bannerList = bannerList;
		this.views = views;
		this.listener = bannerOnClickListener;
//		this.size = bannerList.size();
	}
	
	public void setData(List<BannerInfo> bannerList){
		this.bannerList = bannerList;
		this.size = bannerList.size();
		notifyDataSetChanged();
	}

	@Override
	public int getItemPosition(Object object) {
		return POSITION_NONE;
	}

	@Override
	public int getCount() {
		return size;
	}

	@Override
	public boolean isViewFromObject(View arg0, Object arg1) {
		return arg0 == arg1;
	}

	@Override
	public Object instantiateItem(ViewGroup container, int position) {
		View view = views.get(position);
		if (view == null) {
			view = activity.getLayoutInflater().inflate(R.layout.banner_item, null);
			ImageView img = (ImageView) view.findViewById(R.id.banner_item_image);
			final BannerInfo bannerInfo = bannerList.get(position);
			
//			img.setImageUrl(appendBannerUrl(bannerInfo.getImgUrl()), R.drawable.bg_big_image, R.drawable.bg_big_image);
			GlideUtil.load(activity, appendBannerUrl(bannerInfo.getImgUrl()), R.drawable.bg_big_image, img);

			view.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					listener.click(bannerInfo);
				}
			});
			views.put(position, view);
		}
		if (view.getParent() != null) {
			container.removeView(view);
		}
		container.removeAllViews();
		container.addView(view);
		return view;
	}
	
	//imgUrl +  ?c=0&w=120&h=230&p=0
	private String appendBannerUrl(String imgUrl){
		StringBuffer sb = new StringBuffer(imgUrl);
		sb.append("?c=0&w=");
		sb.append(DefaultConsts.BANNER_DEFAULT_WIDTH);
		sb.append("&h=");
		sb.append(DefaultConsts.BANNER_DEFAULT_HIGHT);
		sb.append("&p=0");
		return sb.toString();
	}

	@Override
	public void destroyItem(ViewGroup container, int position, Object object) {
		container.removeView(views.get(position));
	}

}

